//
// (C) Copyright 2009 Irantha Suwandarathna (irantha@gmail.com)
// All rights reserved.
//

/* Copyright (c) 2001-2008, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use _in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions _in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer _in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */


using System;
using System.Text;
using EffiProz.Core.Lib;
using EffiProz.Core.DataTypes;
using EffiProz.Core.Errors;
using EffiProz.Core.Persist;

namespace EffiProz.Core.RowIO
{
    /**
     *  Provides methods for writing the data for a row to a
     *  byte array. The new format of data consists of mainly binary values
     *  and is not compatible with v.1.6.x databases.
     *
     * @author sqlbob@users (RMP)
     * @author fredt@users
     * @version 1.7.2
     * @since 1.7.0
     */
    public class RowOutputBinary : RowOutputBase
    {
        protected const int INT_STORE_SIZE = 4;
        int storageSize;
        int scale;

        public RowOutputBinary(int initialSize, int scale)
            : base(initialSize)
        {

            this.scale = scale;
        }

        /**
         * Constructor used for network transmission of result sets
         *
         * @param buffer byte[]
         */
        public RowOutputBinary(byte[] buffer)
            : base(buffer)
        {

            scale = 1;
        }

        // fredt@users - comment - methods for writing column type, name and data size
        public override void writeIntData(int i, int position)
        {

            int temp = count;

            count = position;

            writeInt(i);

            if (count < temp)
            {
                count = temp;
            }
        }

        public override void writeData(Object[] data, SqlType[] types)
        {
            base.writeData(data, types);
        }

        public override void writeEnd()
        {

            if (count > storageSize)
            {
                Error.runtimeError(ErrorCode.U_S0500, "RowOutputBinary");
            }

            for (; count < storageSize; )
            {
                this.write(0);
            }
        }

        public override void writeSize(int size)
        {

            storageSize = size;

            writeInt(size);
        }

        public override void writeType(int type)
        {
            writeShort(type);
        }

        public override void writeString(String s)
        {

            int temp = count;

            writeInt(0);

            if (s != null && s.Length != 0)
            {
                StringConverter.stringToUTFBytes(s, this);
                writeIntData(count - temp - INT_STORE_SIZE, temp);
            }
        }

        /**
         *  Calculate the size of byte array required to store a row.
         *
         * @param  row - a database row
         * @return  size of byte array
         * @exception  CoreException When data is inconsistent
         */
        public override int getSize(Row row)
        {

            Object[] data = row.getData();
            SqlType[] types = row.getTable().getColumnTypes();
            int cols = row.getTable().getDataColumnCount();

            return INT_STORE_SIZE + getSize(data, cols, types);
        }

        public override int getStorageSize(int size)
        {
            return scale == 1 ? size
                              : ((size + scale - 1) / scale) * scale;
        }

        protected override void writeFieldType(SqlType type)
        {
            write(1);
        }

        protected override void writeNull(SqlType type)
        {
            write(0);
        }

        protected override void writeChar(String s, SqlType t)
        {
            writeString(s);
        }

        protected override void writeSmallint(short? o)
        {
            writeShort(Convert.ToInt32(o));
        }

        protected override void writeInteger(int? o)
        {
            writeInt(Convert.ToInt32(o));
        }

        protected override void writeBigint(long? o)
        {
            writeLong(Convert.ToInt64(o));
        }

        protected override void writeReal(double? o)
        {
            writeDouble((double)o);
        }

        protected override void writeDecimal(decimal? o, SqlType type)
        {

            writeDecimal((decimal)o);
        }

        protected override void writeBoolean(bool? o)
        {
            writeBool((bool)o);
        }

        protected override void writeDate(TimestampData o, SqlType type)
        {
            writeLong(o.getSeconds());
        }

        protected override void writeTime(TimeData o, SqlType type)
        {

            writeInt(o.getSeconds());
            writeInt(o.getNanos());

            if (type.typeCode == Types.SQL_TIME_WITH_TIME_ZONE)
            {
                writeInt(o.getZone());
            }
        }

        protected override void writeTimestamp(TimestampData o, SqlType type)
        {

            writeLong(o.getSeconds());
            writeInt(o.getNanos());

            if (type.typeCode == Types.SQL_TIMESTAMP_WITH_TIME_ZONE)
            {
                writeInt(o.getZone());
            }
        }

        protected override void writeYearMonthInterval(IntervalMonthData o, SqlType type)
        {
            writeLong(o.units);
        }

        protected override void writeDaySecondInterval(IntervalSecondData o, SqlType type)
        {
            writeLong(o.units);
            writeInt(o.nanos);
        }

        protected override void writeOther(OtherData o)
        {
            writeByteArray(o.getBytes());
        }

        protected override void writeBit(BinaryData o)
        {
            writeInt((int)o.bitLength(null));
            write(o.getBytes(), 0, o.getBytes().Length);
        }

        protected override void writeBinary(BinaryData o)
        {
            writeByteArray(o.getBytes());
        }

        protected override void writeClob(ClobData o, SqlType type)
        {
            writeLong(o.getId());
        }

        protected override void writeBlob(BlobData o, SqlType type)
        {
            writeLong(o.getId());
        }

        // fredt@users - comment - helper and conversion methods
        public void writeByteArray(byte[] b)
        {
            writeInt(b.Length);
            write(b, 0, b.Length);
        }

        // fredt@users - comment - helper and conversion methods
        public void writeCharArray(char[] c)
        {
            writeInt(c.Length);
            write(c, 0, c.Length);
        }

        /**
         * Calculate the size of byte array required to store a row.
         *
         * @param data - the row data
         * @param l - number of data[] elements to include in calculation
         * @param types - array of java.sql.Types values
         * @return size of byte array
         */
        private int getSize(Object[] data, int l, SqlType[] types)
        {

            int s = 0;

            for (int i = 0; i < l; i++)
            {
                Object o = data[i];

                s += 1;    // type or null

                if (o != null)
                {
                    switch (types[i].typeCode)
                    {

                        case Types.SQL_ALL_TYPES:
                            throw Error.runtimeError(ErrorCode.U_S0500,
                                                     "RowOutputBinary");
                        case Types.SQL_CHAR:
                        case Types.SQL_VARCHAR:
                        case Types.VARCHAR_IGNORECASE:
                            s += INT_STORE_SIZE;
                            s += StringConverter.getUTFSize((String)o);
                            break;

                        case Types.TINYINT:
                        case Types.SQL_SMALLINT:
                            s += 2;
                            break;

                        case Types.SQL_INTEGER:
                            s += 4;
                            break;

                        case Types.SQL_BIGINT:
                        case Types.SQL_REAL:
                        case Types.SQL_FLOAT:
                        case Types.SQL_DOUBLE:
                            s += 8;
                            break;

                        case Types.SQL_NUMERIC:
                        case Types.SQL_DECIMAL:
                            s += 16;
                            break;

                        case Types.SQL_BOOLEAN:
                            s += 1;
                            break;

                        case Types.SQL_DATE:
                            s += 8;
                            break;

                        case Types.SQL_TIME:
                            s += 8;
                            break;

                        case Types.SQL_TIME_WITH_TIME_ZONE:
                            s += 12;
                            break;

                        case Types.SQL_TIMESTAMP:
                            s += 12;
                            break;

                        case Types.SQL_TIMESTAMP_WITH_TIME_ZONE:
                            s += 16;
                            break;

                        case Types.SQL_INTERVAL_YEAR:
                        case Types.SQL_INTERVAL_YEAR_TO_MONTH:
                        case Types.SQL_INTERVAL_MONTH:
                            s += 8;
                            break;

                        case Types.SQL_INTERVAL_DAY:
                        case Types.SQL_INTERVAL_DAY_TO_HOUR:
                        case Types.SQL_INTERVAL_DAY_TO_MINUTE:
                        case Types.SQL_INTERVAL_DAY_TO_SECOND:
                        case Types.SQL_INTERVAL_HOUR:
                        case Types.SQL_INTERVAL_HOUR_TO_MINUTE:
                        case Types.SQL_INTERVAL_HOUR_TO_SECOND:
                        case Types.SQL_INTERVAL_MINUTE:
                        case Types.SQL_INTERVAL_MINUTE_TO_SECOND:
                        case Types.SQL_INTERVAL_SECOND:
                            s += 12;
                            break;

                        case Types.SQL_BINARY:
                        case Types.SQL_VARBINARY:
                            s += INT_STORE_SIZE;
                            s += (int)((BinaryData)o).length(null);
                            break;

                        case Types.SQL_BIT:
                        case Types.SQL_BIT_VARYING:
                            s += INT_STORE_SIZE;
                            s += (int)((BinaryData)o).length(null);
                            break;

                        case Types.SQL_CLOB:
                        case Types.SQL_BLOB:
                            s += 8;
                            break;

                        case Types.OTHER:
                            OtherData jo = (OtherData)o;

                            s += INT_STORE_SIZE;
                            s += jo.getBytesLength();
                            break;

                        default:
                            throw Error.runtimeError(ErrorCode.U_S0500,
                                                     "RowOutputBinary");
                    }
                }
            }

            return s;
        }

        /**
         * @param  extra amount of extra space
         */
        public override void ensureRoom(int extra)
        {
            base.ensureRoom(extra);
        }

        public override void reset()
        {

            base.reset();

            storageSize = 0;
        }

        public override void reset(int newSize)
        {

            base.reset(newSize);

            storageSize = 0;
        }

        public override void setBuffer(byte[] buffer)
        {

            this.buf = buffer;

            reset();
        }
    }
}
